package com.autodatabase.xml.model;

import org.dom4j.Attribute;
import org.dom4j.Element;

import com.autodatabase.model.FactoryItemInfo;

public class FactoryItemXmlModel extends FactoryItemInfo{
	/**
	 * 写入FactoryItem信息
	 * @param element
	 */
	public void writeXML(Element element) {
		Element factoryItem = element.addElement("FactoryItem");
		long key = System.currentTimeMillis();
		String strKey = 
			this.getKey() != null && !"".equals(this.getKey()) 
			? this.getKey() : "factoryitem" + "_" + key;
		factoryItem.addAttribute("key", strKey);
		Element itemName = factoryItem.addElement("itemName");
		itemName.addAttribute("value", this.getItemName());
		Element dbType = factoryItem.addElement("dbType");
		dbType.addAttribute("value", this.getDbType() + "");
		Element url = factoryItem.addElement("url");
		url.addAttribute("value", this.getUrl());
		Element userName = factoryItem.addElement("userName");
		userName.addAttribute("value", this.getUserName());
		Element password = factoryItem.addElement("password");
		password.addAttribute("value", this.getPassword());
	}

	/**
	 * 读取FactoryItem信息
	 * @param element
	 */
	public void parseXML(Element element) {
		Element factoryItem = null;
		
		if(!"FactoryItem".equals(element.getName())) {
			factoryItem = element.element("FactoryItem");
		}
		else {
			factoryItem = element;
		}
		
		Attribute key = factoryItem.attribute("key");

		if(key != null) {
			this.setKey(key.getText());
		}

		Element itemName = factoryItem.element("itemName");

		if(itemName != null && itemName.attribute("value") != null) {
			this.setItemName((String) itemName.attribute("value").getData());  
		}
		
		Element dbType = factoryItem.element("dbType");
		
		if(dbType != null && dbType.attribute("value") != null) {
			try {
				Object obj = itemName.attribute("value").getData();
				int dbtype = Integer.parseInt(obj.toString());
				this.setDbType(dbtype);  
			}
			catch(Exception e) {
			}
		}

		Element url = factoryItem.element("url");

		if(url != null && url.attribute("value") != null) {
			this.setUrl((String) url.attribute("value").getData());  
		}

		Element userName = factoryItem.element("userName");

		if(userName != null && userName.attribute("value") != null) {
			this.setUserName((String) userName.attribute("value").getData());  
		}
		
		Element password = factoryItem.element("password");
		
		if(password != null && password.attribute("value") != null) {
			this.setPassword((String) password.attribute("value").getData());  
		}
	}
}
